﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using CRM.UTIL;
using System.Text;
using System.Data;

namespace CRM.WEB.Ajax
{
    public partial class export : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String type = Request["type"];
          
            switch (type)
            {
                case "excel":
                    //数据来源
                    ArrayList data = GetOrderInfo();
                    
                    String json = Request["columns"];
                    ArrayList columns = (ArrayList)JSON.Decode(json);
                    ExportExcel(columns, data,"订单编号");
                    break;
                case "Ali":
                    //数据来源
                    ArrayList dataArr = GetAliOrder();


                    String jsonCol = Request["columns"];
                    ArrayList cols = (ArrayList)JSON.Decode(jsonCol);
                    ExportExcel(cols, dataArr, "OrderList_" + DateTime.Now.ToString("yyyyMMdd"));
                    break;
                case "Parts":
                    var dataParts = GetPartsList();
                    String jsonColumns = Request["columns"];
                    ArrayList colunms = (ArrayList)JSON.Decode(jsonColumns);
                    ExportExcel(colunms, dataParts, "PartsList_" + DateTime.Now.ToString("yyyyMMdd"));
                    break;
                default:
                    break;
            }
        }
        public ArrayList GetOrderInfo()
        {
            //查询条件
            String orderNo = Request["OrderNO"] ?? ""; ;
            String guaranteeNO = Request["guaranteeNO"] ?? "";
            String buyerFullName = Request["buyerFullName"] ?? "";
            String orderDate = Request["orderDate"] ?? "";
            String isDel = Request["isDel"] ?? "";

            //字段排序
            String sortField = Request["sortField"];
            String sortOrder = Request["sortOrder"];

            Hashtable result = GetOrderInfo(orderNo, guaranteeNO, buyerFullName, orderDate, isDel, sortField, sortOrder);
            return result["data"] as ArrayList;
        }

        public Hashtable GetOrderInfo(string orderNo, string guaranteeNO, string buyerFullName, string orderDate, string isDel, string sortField, string sortOrder)
        {
            //System.Threading.Thread.Sleep(300);
            StringBuilder sb = new StringBuilder();
            string sql = string.Format(@"SELECT * FROM OrderInfo WHERE 1=1 ");
            sb.Append(sql);
            if (!string.IsNullOrEmpty(orderNo))
            {
                sb.AppendFormat(@"and  orderNo like '%{0}%' ", orderNo);
            }
            if (!string.IsNullOrEmpty(guaranteeNO))
            {
                sb.AppendFormat(@"and  guaranteeNO like '%{0}%' ", guaranteeNO);
            }
            if (!string.IsNullOrEmpty(buyerFullName))
            {
                sb.AppendFormat(@"and  buyerFullName like '%{0}%' ", buyerFullName);
            }
            if (!string.IsNullOrEmpty(orderDate))
            {
                sb.AppendFormat(@"and  CONVERT(varchar(100), orderDate,23) like '%{0}%' ", orderDate);
            }
            if (!string.IsNullOrEmpty(isDel))
            {
                sb.AppendFormat(@"and  isDel = '%{0}%' ", isDel);
            }
            if (String.IsNullOrEmpty(sortField) == false)
            {
                if (sortOrder != "desc") sortOrder = "asc";
                sql += " order by " + sortField + " " + sortOrder;
            }
            else
            {
                sql += " order by orderDate desc";
            }
            DBChannel db = new DBChannel();
            DataTable dt = db.GetDataBySql(sb.ToString());

            ArrayList dataAll = DataTable2ArrayList(dt);
            ArrayList data = new ArrayList();
            for (int i = 0, l = dataAll.Count; i < l; i++)
            {
                Hashtable record = (Hashtable)dataAll[i];
                if (record == null) continue;

                data.Add(record);

            }
            Hashtable result = new Hashtable();
            result["data"] = data as ArrayList;
            result["total"] = dataAll.Count;

            return result;
        }



        public ArrayList GetAliOrder()
        {
            //字段排序
            String sortField = Request["sortField"] ?? " ID";
            String sortOrder = Request["sortOrder"];


            var isAllocation = Request["isAllocation"] ?? string.Empty;
            var supplierID = Request["supplierID"] ?? string.Empty;
            var warrantyType = Request["warrantyTypeSelect"] ?? string.Empty;
            var serviceStartStart = Request["serviceStartStart"] ?? string.Empty;
            var serviceStartEnd = Request["serviceStartEnd"] ?? string.Empty;
            var serviceEndStart = Request["serviceEndStart"] ?? string.Empty;
            var serviceEndEnd = Request["serviceEndEnd"] ?? string.Empty;
            var country = Request["country"] ?? string.Empty;
            var effectiveSelect = Request["effectiveSelect"] ?? string.Empty;
            var effectiveDateStart = Request["effectiveDateStart"] ?? string.Empty;
            var effectiveDateEnd = Request["effectiveDateEnd"] ?? string.Empty;
            var warrantyStatus = Request["warrantyStatus"] ?? string.Empty;
            var productType = Request["productType"] ?? string.Empty;
            var orderFromType = Request["orderFromType"] ?? string.Empty;
            var hasIssue = Request["hasIssue"] ?? string.Empty;

            //业务操作
            var obj = new BLL.Ali.Ali_OrdersB();
            var stu = new MODEL.Ali.GetAli_Orders
            {
                ORDERSTRING_VALUE = "o." + sortField + " " + sortOrder,
                CURRENTPAGEINDEX_VALUE = 1,
                PAGESIZE_VALUE = int.MaxValue,
                KEYVALUE_VALUE = Request["orderid"] ?? string.Empty,
                BRANDNAMEVALUE = Request["brandName"] ?? string.Empty,
                PRODUCTMODELVALUE = Request["productModel"] ?? string.Empty,
                ORDERDATESTART_VALUE = Request["orderDateStart"] ?? string.Empty,
                ORDERDATEEND_VALUE = Request["orderDateEnd"] ?? string.Empty,
                SERVICESTARTTIMESTART_VALUE = serviceStartStart,
                SERVICESTARTTIMEEND_VALUE = serviceStartEnd,
                SERVICEENDTIMESTART_VALUE = serviceEndStart,
                SERVICEENDTIMEEND_VALUE = serviceEndEnd,
                COUNTRYVALUE = country,
                EFFECTIVE_VALUE = effectiveSelect,
                EFFECTIVEDATESTART_VALUE = effectiveDateStart,
                EFFECTIVEDATEEND_VALUE = effectiveDateEnd,
                WARRANTYSTATUSVALUE=warrantyStatus,
                PRODUCTTYPE_VALUE = productType,
                ORDERFROMTYPE_VALUE=orderFromType,
                HASISSUE_VALUE = hasIssue,
                IDVALUE = Request["id"] ?? string.Empty
            };
            if (isAllocation == "1")
            {
                if (string.IsNullOrEmpty(supplierID))
                    stu.SUPPLIERIDVALUE = -1;
                else
                    stu.SUPPLIERIDVALUE = supplierID;
            }
            else if (isAllocation == "0")
            {
                stu.SUPPLIERIDVALUE = 0;
            }
            var o = SessionBox.GetUserSession();
            if (o != null && (string) o.IsAdmin != "Y")
            {
                stu.SUPPLIERIDVALUE = o.Temp1;
            }
            if (!string.IsNullOrEmpty(warrantyType))
            {
                stu.WARRANTYTYPEVALUE = warrantyType;
            }
            //查询条件
            DataTable dt = obj.GetAli_Orders(ref stu);

            return DataTable2ArrayList(dt);
            //var dataAll = DataTable2ArrayList(dt);

            //ArrayList data = new ArrayList();
            //for (int i = 0, l = dataAll.Count; i < l; i++)
            //{
            //    Hashtable record = (Hashtable)dataAll[i];
            //    if (record == null) continue;

            //    data.Add(record);

            //}

            //return data;
        }

        public ArrayList GetPartsList()
        {
            var partsCategoryID = Request["partsCategoryID"] ?? string.Empty;
            var partsSupplierID = Request["partsSupplierID"] ?? string.Empty;
            var partsModelID = Request["partsModelID"] ?? string.Empty;
            var wisetechNO = Request["wisetechNO"] ?? string.Empty;
            var supplierNO = Request["supplierNO"] ?? string.Empty;
            var procurementProceStart = Request["procurementProceStart"] ?? string.Empty;
            var procurementProceEnd = Request["procurementProceEnd"] ?? string.Empty;
            var marketPriceStart = Request["marketPriceStart"] ?? string.Empty;
            var marketPriceEnd = Request["marketPriceEnd"] ?? string.Empty;
            var stockQtyStart = Request["stockQtyStart"] ?? string.Empty;
            var stockQtyEnd = Request["stockQtyEnd"] ?? string.Empty;

            var keyValue = Request["keyValue"] ?? string.Empty;
            //分页
            int pageIndex = Convert.ToInt32(Request["pageIndex"]);
            int pageSize = Convert.ToInt32(Request["pageSize"]) == 0 ? 10000 : Convert.ToInt32(Request["pageSize"]);

            //字段排序
            String sortField = Request["sortField"] ?? "ID";
            String sortOrder = Request["sortOrder"];



            //业务操作
            var obj = new BLL.PartsB();
            var stu = new MODEL.GetParts()
            {
                ORDERSTRING_VALUE = "p." + sortField + " " + sortOrder,
                CURRENTPAGEINDEX_VALUE = pageIndex + 1,
                PAGESIZE_VALUE = pageSize,
                KEYVALUEVALUE = keyValue,
                IDVALUE = Request["id"] ?? string.Empty,
                CATEGORYIDVALUE = partsCategoryID,
                PARTSSUPPLIERIDVALUE = partsSupplierID,
                PARTSMODELIDSVALUE=partsModelID,
                WISETECHPARTSNOKEYVALUEVALUE = wisetechNO,
                SUPPLIERPARTSNOKEYVALUEVALUE = supplierNO,
                PROCUREMENTPRICESTARTVALUE = procurementProceStart,
                PROCUREMENTPRICEENDVALUE = procurementProceEnd,
                MARKETPRICESTARTVALUE = marketPriceStart,
                MARKETPRICEENDVALUE = marketPriceEnd,
                STOCKQUANTITYSTARTVALUE = stockQtyStart,
                STOCKQUANTITYENDVALUE = stockQtyEnd
            };
            //查询条件
            var isActive = Request["isActive"] ?? string.Empty;
            if (!string.IsNullOrEmpty(isActive))
            {
                if (isActive == "Y")
                    stu.ISAVAILABLEVALUE = true;
                else
                    stu.ISAVAILABLEVALUE = false;
            }

            DataTable dt = obj.GetParts(ref stu);
            return DataTable2ArrayList(dt);
        }



        private static ArrayList DataTable2ArrayList(DataTable data)
        {
            ArrayList array = new ArrayList();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow row = data.Rows[i];

                Hashtable record = new Hashtable();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    object cellValue = row[j];
                    if (cellValue.GetType() == typeof(DBNull))
                    {
                        cellValue = null;
                    }
                    record[data.Columns[j].ColumnName] = cellValue;
                }
                array.Add(record);
            }
            return array;
        }
        public void ExportExcel(ArrayList columns, ArrayList data,string fileName)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            //Response.Charset = "UTF-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            EnableViewState = false;
            Response.Write(ExportTable(data, columns));
            Response.End();

        }
        public static string ExportTable(ArrayList data, ArrayList columns)
        {
            StringBuilder sb = new StringBuilder();
            //data = ds.DataSetName + "\n";
            int count = 0;


            //data += tb.TableName + "\n";
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
            sb.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            //写出列名
            sb.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");
            foreach (Hashtable column in columns)
            {
                sb.AppendLine("<td>" + column["header"] + "</td>");
            }
            sb.AppendLine("</tr>");

            //写出数据
            foreach (Hashtable row in data)
            {
                sb.Append("<tr>");
                foreach (Hashtable column in columns)
                {
                    if (column["field"] == null) continue;
                    Object value = row[column["field"]];
                    sb.AppendLine("<td>" + value + "</td>");

                }
                sb.AppendLine("</tr>");
                count++;
            }
            sb.AppendLine("</table>");


            return sb.ToString();
        }
    }
}